package com.sky.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class TimedTasks {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 取消超时未支付订单
     */
    @Scheduled(fixedDelay = 1000*60) //每分钟执行一次
    public void ProcessingTimeoutsForUnpaidOrders(){
        log.info("开始扫描超时未支付订单");
        //查询15分钟内，未支付的订单
        OrdersPageQueryDTO queryDTO = new OrdersPageQueryDTO();
        queryDTO.setStatus(Orders.UN_PAID);
        queryDTO.setEndTime(LocalDateTime.now().minusMinutes(15));
        List<OrderVO> orders = orderMapper.SelectHistoryOrdersByPage(queryDTO);
        log.info("超时订单为：{}",orders);
        //取消订单
        if (ObjectUtil.isNotNull(orders)){
            for (OrderVO order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("超时未支付，订单自动取消！");
                orderMapper.update(order);
                log.info("订单取消:{}",order);
            }
        }
    }

    @Scheduled(cron = "0 0 2 * * ?")
    //@Scheduled(fixedDelay = 1000*60)
    public void completeDeliveryOrder(){
        log.info("自动扫描派送中订单");
        //查询所有配送中订单
        LocalDateTime time = LocalDateTime.now().minusHours(2);  // 每天凌晨
        Date dateTime = new DateTime(time);
        log.info("清理时间点为：{}",dateTime);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersPageQueryDTO.setBeginTime(DateUtil.toLocalDateTime(DateUtil.beginOfDay(dateTime)));
        ordersPageQueryDTO.setEndTime(DateUtil.toLocalDateTime(DateUtil.endOfDay(dateTime)));
        log.info("开始时间--->{}",ordersPageQueryDTO.getBeginTime());
        log.info("结束时间--->{}",ordersPageQueryDTO.getEndTime());
        List<OrderVO> orders = orderMapper.SelectHistoryOrdersByPage(ordersPageQueryDTO);


        //完成订单
        if (CollUtil.isEmpty(orders)){
            throw new OrderBusinessException("订单不存在！");
        }
        for (OrderVO order : orders) {
            log.info("派送中的订单为：{}",order);
            order.setStatus(Orders.COMPLETED);
            orderMapper.update(order);
            log.info("自动完成订单");
        }
    }
}
